var modelCanvas = null;
var paperCanvas = null;

var modelView = null;
var paperView = null;

window.addEventListener("load", function() {
    modelCanvas = document.getElementById("model-3d-canvas");
    modelCanvas.width = window.innerWidth;
    modelCanvas.height = window.innerHeight;
    paperCanvas = document.getElementById("crease-pattern-canvas");
    var model = createEmptyPaper(1000, 1414, 0.1);
    modelView = new Model3DViewer(modelCanvas, model);
    paperView = new CreasePatternViewer(paperCanvas, model);
    paperView.setSize(window.innerWidth * 0.5, window.innerHeight * 0.618);
    
    modelView.start();
    paperView.draw();
    paperView.creaseCreated(function(start, end, patch) {
        start = changeCoordinatePoint3(start, patch.coordinate, normalCoordinate);
        end = changeCoordinatePoint3(end, patch.coordinate, normalCoordinate);
        var selectedLine = { start: start, end: end };
        var angle = parseFloat(document.getElementById("angle-input").value);
        if (isNaN(angle)) {
            angle = 180;
            document.getElementById("angle-input").value = angle.toString();
        }
        foldSinglePlane(model, model.planes[0], selectedLine, angle, true);
        modelView.refreshModel();
    });

    paperView.pointTouched(function(point, patch) {
        point = changeCoordinatePoint3(point, patch.coordinate, normalCoordinate);
        modelView.removeAllSelectedPoints();
        modelView.addSelectedPoint(point);
    });

    paperView.setFoldingTool(paperView.FOLD_LINES);

    document.getElementById("folding-tool-selector").addEventListener("click", function() {
        var selections = document.getElementsByName("folding-tool-type");
        var value = "";
        for (var i = 0; i < selections.length; i++) {
            if (selections[i].checked) {
                value = selections[i].value;
                break;
            }
        }
        if (value == "line-folding") {
            paperView.setFoldingTool(paperView.FOLD_LINES);
        }
        else if (value == "point-folding") {
            paperView.setFoldingTool(paperView.FOLD_POINTS);
        }
        else if (value == "crease-creator") {
            paperView.setFoldingTool(paperView.CREATE_CREASE);
        }
    });

    document.getElementById("smart-selection-checker").addEventListener("click", function() {
        var checkBox = document.getElementsByName("smart-select");
        paperView.setSmartSelection(checkBox[0].checked);
    })
});

window.addEventListener("resize", function() {
    if (modelCanvas && modelView) {
        modelView.resetViewport(window.innerWidth, window.innerHeight);
    } 
    if (paperCanvas && paperView) {
        paperView.setSize(window.innerWidth * 0.5, window.innerHeight * 0.618);
        paperView.draw();
    }
});